import { createRouter, createWebHistory,createWebHashHistory } from 'vue-router'

import Layout from "@/views/layout/index.vue";
// 具名导出routes
export const menus = [
  {
    path: '/login',
    hidden: true,
    name: "login",
    component: () => import('@/views/login/index.vue')
  },
  {
    path: '/',
    label: '首页',
    name:'home',
    component: Layout,
  },
  {
    path: '/banner',
    label: '轮播图',
    component: Layout,
    children: [
      { path: 'list', label: "轮播图列表", component: () => import('@/views/banner/list.vue') },
      { path: 'add', label: "轮播图添加", component: () => import('@/views/banner/add.vue') },
    ]
  },
  {
    path: '/manager',
    label: "管理员",
    component: Layout,
    children: [
      { path: "list", label: "管理员列表", component: () => import('@/views/manager/list.vue') },
      // { path: "add", label: "管理员添加", component: () => import('@/views/manager/add.vue') },
    ]
  },

]
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  // history:createWebHashHistory(),
  routes: menus
})

const whiteList = ["login"];

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const name = to.name;

  if (whiteList.includes(name)) {
    // 存在，说明这个to不需要校验登录，直接放行
    next();
  } else {
    // 不存在,需要校验登录状态
    const token = localStorage.getItem("token");
    if (token) {
      // 登录了，直接放行
      next();
    } else {
      // 没登录，需要重定向到登录页面
      next({ name: "login" });
    }
  }
});
export default router
